#include "footmarkeditview.h"

#include "../../../uitools/IdRootMenu.h"
#include "keconst/ConstTeNormal.h"
#include "../../../uitools/vhc/constview4fun.h"
#include "../../../uitools/vhc/constview4id.h"
#include "../../../uitools/vhc/dataupdatecomm.h"

#include "kegui/rwidgets/ketoast/kemultilabel.h"
#include "kegui/rwidgets/ketoast/KePopupToast.h"
#include "kegui/rwidgets/ketoast/kelabeltoast.h"
#include "kegui/rwidgets/ketoast/kestringtoast.h"

#include "it_comm_fm.h"


#include <QHBoxLayout>
#include <QLabel>
#include <QPushButton>
#include <QLineEdit>
#include <QFontDatabase>
#include <QFileInfo>

#include <QModelIndexList>
#include <QRegularExpression>

#include <QDebug>

namespace kepen {
namespace core {


FootmarkEditView::FootmarkEditView(QWidget *parent,kepen::kemod::KeFootmark *node,KeSysSetting *sys)
    : QWidget{parent}
{

    indexTmp = 0;

    if(NULL == node)
    {
        flag = New_Record;
        hashNode = 0;
        std::unique_ptr<kepen::kemod::KeFootmark> p(std::make_unique<kepen::kemod::KeFootmark>());
        nodePtr.swap(p);
    }else
    {
        flag = Update_Record;
        hashNode=node->getHash31();
        std::unique_ptr<kepen::kemod::KeFootmark> p=node->clone();
        nodePtr.swap(p);
    }
    initWidget(sys);
}

FootmarkEditView::~FootmarkEditView()
{

}

void FootmarkEditView::setDataSource(kepen::core::MapObject *map, kepen::kemod::KeFootmarkDao *d)
{
    mapSurface=map;
    dao=d;
}

kepen::kemod::KeFootmark *FootmarkEditView::getData()
{
    return nodePtr.get();
}



void FootmarkEditView::initWidget(KeSysSetting *conf)
{
    QString nameThiz("FootmarkEditBody");
    QString backcolorBody= QString::asprintf("#%08x",Widget_Body_Background);
    QString cssThiz = QString("QWidget#%1{background-color:%2;font-size:%3px;border:0px;border-style:none;}")
                          .arg(nameThiz)
                          .arg(backcolorBody)
                          .arg(TextSize_ToolBar);


    setContentsMargins(0, 0, 0, 0);
    setObjectName(nameThiz);
    setStyleSheet(cssThiz);


    int fontId = QFontDatabase::addApplicationFont(conf->configView()->fileIconFont);
    QString fontName = QFontDatabase::applicationFontFamilies(fontId).at(0);
    QFont fontIcon = QFont(fontName);
    fontIcon.setPointSize(TextSize_IconFont);

    QVBoxLayout  *verticalLayout = new QVBoxLayout(this);
    verticalLayout->setObjectName("verticalLayoutMain");
    verticalLayout->setSpacing(0);
    verticalLayout->setContentsMargins(0, 0, 0, 0);
    verticalLayout->setAlignment(Qt::AlignmentFlag::AlignLeft|Qt::AlignmentFlag::AlignTop);


    QWidget *widget_head = buildHead(this,fontIcon);

    verticalLayout->addWidget(widget_head);
    ADD_VerSpace(verticalLayout);

    QWidget * name = buildInputItem(this,&inputName,"名称",40);
    verticalLayout->addWidget(name);
    ADD_VerSpace(verticalLayout);

    QWidget * addr = buildInputItem(this,&inputAddr,"地址",60);
    verticalLayout->addWidget(addr);
    ADD_VerSpace(verticalLayout);

    QWidget * locate = buildLocate(this,fontIcon);
    verticalLayout->addWidget(locate);
    QWidget * coords = buildInputItem2(this,&inputCoords,40);
    verticalLayout->addWidget(coords);
    ADD_VerSpace(verticalLayout);

    QWidget * remark = buildInputItem(this,&inputRemark,"备注",60);
    verticalLayout->addWidget(remark);
    ADD_VerSpace(verticalLayout);


    verticalLayout->addSpacerItem(new QSpacerItem(60,4, QSizePolicy::Expanding, QSizePolicy::Policy::Fixed));


    QRegularExpression regExp("^[a-zA-Z0-9\u00b7\\+\\(\\-\\)\\$!@#^&\u4e00-\u9fa5]+$");
    QRegularExpressionValidator *pReg = new QRegularExpressionValidator(regExp, name);
    inputName->setValidator(pReg);
    inputAddr->setValidator(pReg);

    // QString _mask("0-9\\s\\.\\+\\-\\,\\;\\'\\`");
    // inputCoords->setInputMask(_mask);
    QRegularExpression reCoords("^[0-9\\s\\.\\+\\-\\,\\;\\'\\`]+$");
    QRegularExpressionValidator *pRegCoords = new QRegularExpressionValidator(reCoords, name);
    inputAddr->setValidator(pRegCoords);

    if(Update_Record == flag)
    {
        nodeValue2View();
    }
}

QWidget *FootmarkEditView::buildHead(QWidget *parent, QFont &fontIcon)
{
    bool isNew = nodePtr->name.isEmpty();
    int _w = 2 + Height_TileHead, _h = Height_TileHead;

    QString nameTileHead("widget_E_head");
    QString backcolorHead = QString::asprintf("#%08x",Color_HeadPanel_Background);
    QString cssTileHead = QString("QWidget#%1{background-color:%2;font-size:%3px;border:0px;border-style:none;}")
                              .arg(nameTileHead).arg(backcolorHead).arg(TextSize_ToolBar);

    QString cssBtn = QCSS_IconBtnTileHead();
    QString cssLabel = QString::asprintf("QLabel{background-color:transparent;color:#%08x;border:0px;font-size:%dpx;}"
                                         ,Color_HeadPanel_Label,TextSize_ToolBar);


    QWidget *widget_head = new QWidget(parent);

    widget_head->setObjectName(nameTileHead);
    widget_head->setStyleSheet(cssTileHead);

    QSizePolicy sizePolicy(QSizePolicy::Policy::Preferred, QSizePolicy::Policy::Fixed);
    sizePolicy.setHorizontalStretch(0);
    sizePolicy.setVerticalStretch(0);
    sizePolicy.setHeightForWidth(widget_head->sizePolicy().hasHeightForWidth());
    widget_head->setSizePolicy(sizePolicy);
    widget_head->setFixedHeight(_h);

    QHBoxLayout* headLay = new QHBoxLayout(widget_head);
    headLay->setObjectName("horizonLayoutHead");
    headLay->setSpacing(0);
    headLay->setContentsMargins(0, 0, 0, 0);
    headLay->setAlignment(Qt::AlignmentFlag::AlignLeft|Qt::AlignmentFlag::AlignTop);



    QPushButton* btnClose = new QPushButton("\ue634",widget_head);
    btnClose->setFont(fontIcon);
    btnClose->setStyleSheet(cssBtn);
    btnClose->setFixedSize(_w,_h);

    headLay->addWidget(btnClose);

    headLay->addSpacerItem(new QSpacerItem(4,_h, QSizePolicy::Fixed, QSizePolicy::Policy::Fixed));

    char nas[64];
    std::sprintf(nas,"添加\u0020%s",Name_Tab_View);
    QString na(nas);

    QString nodeName = isNew ?(na):nodePtr->name;

    QLabel*headLabel = new QLabel(nodeName, widget_head);

    headLabel->setStyleSheet(cssLabel);
    headLabel->adjustSize();
    // pLabel-> setMinimumSize(pLabel->size().width(), pLabel->size().height());
    // m_pLabel->move(0, (height() - m_pLabel->height()) / 2);
    headLay->addWidget(headLabel);

    headLay->addSpacerItem(new QSpacerItem(4,_h, QSizePolicy::Expanding, QSizePolicy::Policy::Fixed));



    QPushButton* btnSave = new QPushButton(TEXT_Icon_Save,widget_head);
    btnSave->setFont(fontIcon);
    btnSave->setStyleSheet(cssBtn);
    btnSave->setFixedSize(_w,_h);
    headLay->addWidget(btnSave);

    headLay->addSpacerItem(new QSpacerItem(2,_h, QSizePolicy::Fixed, QSizePolicy::Policy::Fixed));

    // connect(btnClose, &QPushButton::clicked, [&]() {
    //     Q_EMIT onTabViewClosed(this);
    // });



    connect(btnClose, &QPushButton::clicked, this, &FootmarkEditView::onBtnCloseClicked);
    connect(btnSave, &QPushButton::clicked, this, &FootmarkEditView::onBtnSaveClicked);


    return widget_head;
}

QWidget *FootmarkEditView::buildInputItem(QWidget *parent,QLineEdit **input,const char*label,int maxLength)
{
    quint32 indexA = ++indexTmp;
    int h = Height_input_Default;


    QString cssInput = QCSS_Input();
    QString nameWidgetThiz = QString::asprintf("EBW_%d",indexA);
    QString nameLay = QString::asprintf("Edit_BodyLay_%d",++indexTmp);

    QString cssLabel = QString::asprintf("QLabel{background-color:transparent;color:#%08x;border:0px;font-size:%dpx;}"
                                         ,Color_HeadPanel_Label,TextSize_ToolBar);
    QString cssWidgetThiz = QString::asprintf("QWidget#EBW_%d{background-color:transparent;font-size:%dpx;}"
                                              ,indexA,TextSize_ToolBar);


    QSizePolicy sizePolicy(QSizePolicy::Policy::Expanding, QSizePolicy::Policy::Fixed);
    sizePolicy.setHorizontalStretch(0);
    sizePolicy.setVerticalStretch(0);
    sizePolicy.setHeightForWidth(parent->sizePolicy().hasHeightForWidth());

    QWidget *widget_t = new QWidget(parent);

    widget_t->setObjectName(nameWidgetThiz);
    widget_t->setStyleSheet(cssWidgetThiz);

    widget_t->setSizePolicy(sizePolicy);
    widget_t->setFixedHeight(h);

    QHBoxLayout* horizLay = new QHBoxLayout(widget_t);
    horizLay->setObjectName(nameLay);
    horizLay->setSpacing(0);
    horizLay->setContentsMargins(0, 0, 0, 0);
    horizLay->setAlignment(Qt::AlignmentFlag::AlignLeft|Qt::AlignmentFlag::AlignTop);


    QLabel*headLabel = new QLabel(label, widget_t);

    headLabel->setStyleSheet(cssLabel);
    headLabel->adjustSize();

    horizLay->addWidget(headLabel);
    horizLay->addSpacerItem(new QSpacerItem(Pad_Body_Right,h, QSizePolicy::Fixed, QSizePolicy::Policy::Fixed));

    QLineEdit * _input= new QLineEdit(widget_t);

    _input->setSizePolicy(sizePolicy);
    _input->setFixedHeight(h);

    _input->setClearButtonEnabled(true);
    // verticalLayout->addWidget(_input);
    _input->setStyleSheet(cssInput);
    _input->setMaxLength(maxLength);

    // _input->installEventFilter(this);
    _input->setFocusPolicy(Qt::StrongFocus);

    // connect(_input, SIGNAL(returnPressed()), this, SLOT(onInputSearch()));

    *input = _input;

    horizLay->addWidget(_input);
    horizLay->addSpacerItem(new QSpacerItem(Pad_Body_Right,h, QSizePolicy::Fixed, QSizePolicy::Policy::Fixed));

    return widget_t;
}


QWidget *FootmarkEditView::buildInputItem2(QWidget *parent,QLineEdit ** input,int maxLength)
{
    quint32 indexA = ++indexTmp;
    int h = Height_input_Default;


    QString cssInput = QCSS_Input();
    QString nameWidgetThiz = QString::asprintf("EBW_%d",indexA);
    QString nameLay = QString::asprintf("Edit_BodyLay_%d",++indexTmp);

    QString cssLabel = QString::asprintf("QLabel{background-color:transparent;color:#%08x;border:0px;font-size:%dpx;}"
                                         ,Color_HeadPanel_Label,TextSize_ToolBar);
    QString cssWidgetThiz = QString::asprintf("QWidget#EBW_%d{background-color:transparent;font-size:%dpx;}"
                                              ,indexA,TextSize_ToolBar);


    QSizePolicy sizePolicy(QSizePolicy::Policy::Expanding, QSizePolicy::Policy::Fixed);
    sizePolicy.setHorizontalStretch(0);
    sizePolicy.setVerticalStretch(0);
    sizePolicy.setHeightForWidth(parent->sizePolicy().hasHeightForWidth());

    QWidget *widget_t = new QWidget(parent);

    widget_t->setObjectName(nameWidgetThiz);
    widget_t->setStyleSheet(cssWidgetThiz);

    widget_t->setSizePolicy(sizePolicy);
    widget_t->setFixedHeight(h);

    QHBoxLayout* horizLay = new QHBoxLayout(widget_t);
    horizLay->setObjectName(nameLay);
    horizLay->setSpacing(0);
    horizLay->setContentsMargins(0, 0, 0, 0);
    horizLay->setAlignment(Qt::AlignmentFlag::AlignLeft|Qt::AlignmentFlag::AlignTop);


    QLineEdit * _input= new QLineEdit(widget_t);

    _input->setSizePolicy(sizePolicy);
    _input->setFixedHeight(h);

    _input->setClearButtonEnabled(true);
    // verticalLayout->addWidget(_input);
    _input->setStyleSheet(cssInput);
    _input->setMaxLength(maxLength);

    // _input->installEventFilter(this);
    _input->setFocusPolicy(Qt::StrongFocus);

    // connect(_input, SIGNAL(returnPressed()), this, SLOT(onInputSearch()));

    *input = _input;

    horizLay->addWidget(_input);
    horizLay->addSpacerItem(new QSpacerItem(Pad_Body_Right,h, QSizePolicy::Fixed, QSizePolicy::Policy::Fixed));

    return widget_t;
}

QWidget *FootmarkEditView::buildLocate(QWidget *parent, QFont &fontIcon)
{
    const char *label = "位置坐标(经纬度)";
    int h = Height_input_Default;
    int _w = 2 + Height_TileHead;
    quint32 indexA = ++indexTmp;
    QString cssBtn = QCSS_IconBtnToolBar();
    QString cssInput = QCSS_Input();
    QString nameWidgetThiz = QString::asprintf("EBW_%d",indexA);
    QString nameLay = QString::asprintf("Edit_BodyLay_%d",++indexTmp);

    QString cssLabel = QString::asprintf("QLabel{background-color:transparent;color:#%08x;border:0px;font-size:%dpx;}"
                                         ,Color_HeadPanel_Label,TextSize_ToolBar);
    QString cssWidgetThiz = QString::asprintf("QWidget#EBW_%d{background-color:transparent;font-size:%dpx;}"
                                              ,indexA,TextSize_ToolBar);



    QSizePolicy sizePolicy(QSizePolicy::Policy::Expanding, QSizePolicy::Policy::Fixed);
    sizePolicy.setHorizontalStretch(0);
    sizePolicy.setVerticalStretch(0);
    sizePolicy.setHeightForWidth(parent->sizePolicy().hasHeightForWidth());

    QWidget *widget_t = new QWidget(parent);

    widget_t->setObjectName(nameWidgetThiz);
    widget_t->setStyleSheet(cssWidgetThiz);

    widget_t->setSizePolicy(sizePolicy);
    widget_t->setFixedHeight(h);

    QHBoxLayout* horizLay = new QHBoxLayout(widget_t);
    horizLay->setObjectName("horizonLayoutSearch");
    horizLay->setSpacing(0);
    horizLay->setContentsMargins(0, 0, 0, 0);
    horizLay->setAlignment(Qt::AlignmentFlag::AlignLeft|Qt::AlignmentFlag::AlignTop);


    QLabel*headLabel = new QLabel(label, widget_t);

    headLabel->setStyleSheet(cssLabel);
    headLabel->adjustSize();

    horizLay->addWidget(headLabel);

    horizLay->addSpacerItem(new QSpacerItem(16,h, QSizePolicy::Fixed, QSizePolicy::Policy::Fixed));


    QPushButton* btnClose = new QPushButton("\ue7bf",widget_t);
    btnClose->setFont(fontIcon);
    btnClose->setStyleSheet(cssBtn);
    btnClose->setFixedSize(_w,h);

    horizLay->addWidget(btnClose);


    return widget_t;
}

void FootmarkEditView::view2NodeValue()
{

    static   QRegularExpression spaceRex("\\s");
    //QString::simplified()方法会移除字符串首尾的空格，并将字符串中间的连续空格替换为一个单个空格
    QString name = inputName->text();
    QString address = inputAddr->text();
    QString coords = inputCoords->text();
    QString remark = inputRemark->text();

    RemoveQStrSpace(name)
        RemoveQStrSpace(address)
        RemoveQStrSpace(remark)

        nodePtr->name = name;
    nodePtr->address = address;
    nodePtr->remark = remark;
    if(false == coords.isEmpty())
    {
        double x=0.0,y=0.0;
        bool b = tyrParsePointCoords(coords,x,y);
        if(b){
            nodePtr->lng = x;
            nodePtr->lat = y;
        }else{
            nodePtr ->setNullGeom();
        }
    }else{
        nodePtr ->setNullGeom();
    }
}

void FootmarkEditView::nodeValue2View()
{
    inputName->setText(nodePtr->name);
    inputAddr->setText(nodePtr->address);
    if(false == nodePtr->remark.isEmpty())
        inputRemark->setText(nodePtr->remark);
    if(false == nodePtr->isNullGeom())
    {
        QString coord = QString::asprintf("%.6f,%.6f",nodePtr->lng,nodePtr->lat);
        inputCoords->setText(coord);
    }
}

bool FootmarkEditView::tyrParsePointCoords(const QString txt, double &x, double &y)
{
    bool ret = false;

    if(txt.isEmpty()||txt.isNull()){

    }else
    {
        QString str = txt.simplified();

        if(str.isEmpty()||str.isNull()){

        }else
        {

            char ch,sp, f1 = '\0',f2 ='\0';
            qsizetype i,len;
            QByteArray chars = str.toLocal8Bit();
            len = chars.length();
            for (i = 0; i < len; i++)
            {
                ch = chars[i];
                if((ch>='0' && ch <= '9') || '-' == ch||'+' == ch || '.'== ch)
                {

                    continue;
                }
                else
                {
                    if(' '==ch)
                        f1 = ch;
                    else
                        f2 = ch ;

                }
            }


            sp = '\0'== f2 ? f1 :f2;

            if (sp != '\0'){
                QChar sep(sp);
                QStringList sl = str.split(sep);
                if(2 == sl.count())
                {
                    bool ok0,ok1;
                    double d0,d1;
                    QString szX = sl[0];
                    QString szY = sl[1];
                    // qDebug()  <<__FILE__ <<",Line:"<<__LINE__ << "str(x,y):"<<szX << ", " <<szY;
                    if(false == (szX.isEmpty()||szX.isNull())
                        && false == (szY.isEmpty()||szY.isNull())){
                        d0 = szX.toDouble(&ok0);
                        d1 = szY.toDouble(&ok1);
                        if(ok0 && ok1)
                        {
                            x = d0;
                            y = d1;
                            return true;
                        }
                    }
                }
            }

        }
    }

    return ret;
}



void FootmarkEditView::popHintMsg(QLineEdit *input, const QString &msg)
{
    int h,y,h2;

    KePopupToast * wPopup = new KePopupToast(this,msg);
    QPoint globalPos = this->mapToGlobal(input->pos());
    h2 = wPopup->height();
    h = input->height();
    y = globalPos.y();
    y+= (h+h2 +Yoff_pop_Tmp);
    //背景黑色，有圆角，明显不对
    // wPopup->bgColor = 0xff868686U;

    globalPos.setY(y);
    wPopup->showAt(4000,globalPos);

    input->setFocus(Qt::FocusReason::OtherFocusReason);
}




void FootmarkEditView::onBtnCloseClicked()
{
    quint32 h,d,f;
    view2NodeValue();

    h = nodePtr->getHash31();
    d = h == hashNode ? 0 : Changed_Record;
    f = d | flag;

    Q_EMIT stackedWidgetClosed(f,this);


    // this->deleteLater();
}



void FootmarkEditView::onBtnSaveClicked()
{
    view2NodeValue();
    if(nodePtr->name.isEmpty())
    {
        popHintMsg(inputName,QStringLiteral("名称不能为空"));

        return;
    }
    if(nodePtr->address.isEmpty())
    {
        popHintMsg(inputAddr,QStringLiteral("地址不能为空"));

        return;
    }
    if(nodePtr->isNullGeom())
    {
        popHintMsg(inputCoords,QStringLiteral("位置坐标不能为空"));
        return;

    }

    if(dao)
    {
        kepen::kemod::KeFootmark *node= nodePtr.get();
        std::vector<std::unique_ptr<kepen::kemod::KeFootmark>> vs;
        dao->select4NameUnique(node,&vs);

        if(vs.size()>0)
        {
            int h,y,h2;
            QStringList vsStr;
            vsStr << QStringLiteral("名称不能重复");
            auto &it = vs[0];
            vsStr << it->name ;
            if(0==QString::compare(it->updateTime, it->createTime, Qt::CaseSensitive))
            {
                vsStr <<  QStringLiteral("创建日期:%1").arg(it->createTime);
            }else{
                vsStr << QStringLiteral("修改日期:%1").arg(it->updateTime);
                vsStr <<  QStringLiteral("创建日期:%1").arg(it->createTime);
            }

            KeMultiLabel *wPopup = new KeMultiLabel(this,vsStr);
            QPoint globalPos = this->mapToGlobal(inputName->pos());
            h2 = wPopup->height();
            h = inputName->height();
            y = globalPos.y();
            y+= (h+h2 +Yoff_pop_Tmp);

            globalPos.setY(y);
            wPopup->showAt(8000,globalPos);

            inputName->setFocus(Qt::FocusReason::OtherFocusReason);

            return;

        }

        if(0 == node->version)
        {
            dao->insertMode(node );
        }else
        {
            dao->updateMode(node);
        }



    }
}

}
}
